/**
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @author opensource@google.com
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

// Global variables.
var queryEl = document.getElementById('query');
var nodeCountEl = document.getElementById('node-count');
var refreshEl = document.getElementById('refresh');
var listEl = document.getElementById('result-list');

var nodeCountText = document.createTextNode('0');
nodeCountEl.appendChild(nodeCountText);

// Used by handleMouseMove() to enforce a cool-down period on relocate.
var mostRecentRelocateTimeInMs = 0;

var evaluateQuery = function() {
  if( refreshEl.checked ) {
    var message = {
      'dest': chrome.devtools.inspectedWindow.tabId,
      'type': 'evaluate',
      'query': queryEl.value
    };
    chrome.extension.sendRequest(message);
  }
};

var handleRequest = function(message, sender, callback) {
  // Note: Setting textarea's value and text node's nodeValue is XSS-safe.
  if (message['type'] == 'update') {
    if (message['query'] != null) {
      queryEl.value = message['query'];
    }
    if (message['results'] != null) {
      nodeCountText.nodeValue = message['results'][0];
      while( listEl.hasChildNodes() ) {
        listEl.removeChild(listEl.lastChild);
      }
      var resList = message['results'][1];
      var attribList = message['results'][2];
      for( var i=0; i<resList.length; i++ ) {
        var tr = document.createElement( 'tr' );
        var td1 = document.createElement( 'td' );
        var td2 = document.createElement( 'td' );
        td1.textContent = JSON.stringify( attribList[i] );
        tr.appendChild( td1 );
        td2.textContent = resList[i];
        tr.appendChild( td2 );
        listEl.appendChild( tr );
      }
    }
  }
};

queryEl.addEventListener('keyup', evaluateQuery, false);
queryEl.addEventListener('mouseup', evaluateQuery, false);
refreshEl.addEventListener('change', evaluateQuery, false);

chrome.extension.onRequest.addListener(handleRequest);
